#!/usr/bin/env python
# -*- coding: utf-8 -*-

''' output like this:
{'mem': {'swaptotal': 4095, 'memtotal': 3832}, 'disk': {'sda': '293.4'}, 'cpu': {'0': {'cores': '4', 'name': 'Intel(R) Xeon(R) CPU           E5405  @ 2.00GHz', 'processor': 4}}}
'''

import subprocess
result = {'cpu':{},'mem':{},'disk':{}}

def hwCpu():
    cpu_id = set()
    with open('/proc/cpuinfo','r') as f:
        data = f.read().strip().split('\n\n')
    
    for i in data:
        id = subprocess.Popen(("echo '%s'|grep '^physical id'|cut -d: -f2" % i),shell=True,stdout=subprocess.PIPE).stdout.read().strip()
        if not id:id = 0
        if id in cpu_id:
            result['cpu'][id]['processor'] += 1
        else:
            result['cpu'][id] = {}
            result['cpu'][id]['name'] = subprocess.Popen(("echo '%s'|grep '^model name'|cut -d':' -f2" % data[0]),shell=True,stdout=subprocess.PIPE).stdout.read().strip()
            cores = subprocess.Popen(("echo '%s'|grep '^cpu cores'|cut -d':' -f2" % data[0]),shell=True,stdout=subprocess.PIPE).stdout.read().strip()
            if not cores: cores = 1
    	    result['cpu'][id]['cores'] = cores
            result['cpu'][id]['processor'] = 1
            cpu_id.add(id)

def hwMem():
    result['mem']['memtotal'] = int(subprocess.Popen("grep '^MemTotal' /proc/meminfo|awk '{print $2}'",shell=True,stdout=subprocess.PIPE).stdout.read().strip()) / 1024
    result['mem']['swaptotal'] = int(subprocess.Popen("grep '^SwapTotal' /proc/meminfo|awk '{print $2}'",shell=True,stdout=subprocess.PIPE).stdout.read().strip()) / 1024

def hwDisk():
    data = subprocess.Popen("fdisk -l 2> /dev/null |grep '^Disk /dev/[s|h|v]d.' | awk '{print $2 $3}' | cut -d'/' -f3",shell=True,stdout=subprocess.PIPE).stdout.readlines()
    for i in data:
        name,size = i.strip().split(':')
        result['disk'][name] = size
hwCpu()
hwMem()
hwDisk()
print result
